var sidebar = {
  selectedTag : null,

  init : function(){
    var gBrowser = mainWindow.getBrowser();
    gBrowser.addProgressListener(urlBarListener,Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
    var currentUri = getURL() + "";
	  if(currentUri == "" || (currentUri.substring(0, "about:".length) == "about:")){

	  }else{
	    this.doUriChange(currentUri);
	    this.doDocumentLoaded();
	  }
  },

  doUriChange : function(uri){
    //return false;
    proxy.init();
    proxy.setUri(uri);
    proxy.getViewpoints();
    proxy.getColorTopics();
    proxy.getFragments();
    proxy.getPorps();
    this.showEntityList();
    this.showFragments();
    this.showFragmentsInViewpoints();
    //highlighter.doFormatHtml();
    debug("[lasuliSidebar.js::doUriChange] uri:"+ uri, 2);
  },

	doDocumentLoaded: function(){
		if(mainWindow.getBrowser() != null){
			var docSrc = mainWindow.getBrowser().contentDocument.documentElement.innerHTML;
			if(docSrc == null || docSrc.indexOf("highlighted_by_hypertopic_sidebar") > 0)
				return;

    	htData.docHtml = docSrc;
      highlighter.doFormatHtml();
    	debug("[lasuliSidebar.js::doDocumentLoaded] doDocumentLoaded:" + docSrc, 5);
    }else
    	debug("[lasuliSidebar.js::doDocumentLoaded] doLocationChange exception gBrowser is NULL", 2);
	},

  doHighlight: function(fragment){
    var viewpointUri = sidebar.getSelectedPanelViewpointUri();
    debug("[lasuliSidebar.js::doHighlight] highlighted viewpoint panel: "+viewpointUri, 3);
    var res = proxy.addFragment(fragment, viewpointUri);
    debug("[lasuliSidebar.js::doHighlight] save result: "+res, 3);
    if(res){
			sidebar.showFragments();
			sidebar.showFragmentsInViewpoints();
			if(viewpointUri != null)
			  showTagCloud(viewpointUri);
			highlighter.doFormatHtml();
		}
  },

  doFilterViewpoints : function(){
    //debug("[lasuliSidebar.js::doFilterViewpoints]", 4);
    var puEntityList = document.getElementById('puEntityList');
    var items = puEntityList.getElementsByTagName('menuitem');
    for(var i=0; i < items.length; i++)
      if(items[i].hasAttribute("checked")){
        //debug("[lasuliSidebar.js::doFilterViewpoints] found", 4);
        this.showViewpoints(items[i].getAttribute("href"));
        break;
      }
    if(items.length == 0){
      this.showViewpoints();
      debug("[lasuliSidebar.js::doFilterViewpoints] entity list is null", 3);
    }
  },

  doEntityChange : function(e){
    var menuitem = e.srcElement || e.target;
    var captionEntity = document.getElementById('captionEntity');
    captionEntity.label = menuitem.label;
    sidebar.showPorps(menuitem.getAttribute("href"));
    debug("[lasuliSidebar.js::doEntityChange] menuitem.href:" + menuitem.getAttribute("href") , 3);
  },
  doContextMenuRenameTag: function(){
    debug("[lasuliSidebar.js::doContextMenuRenameTag] selectedTag:" + sidebar.selectedTag.getAttribute("uri"), 3);
    debug("[lasuliSidebar.js::doContextMenuRenameTag] selectedTag:" + sidebar.selectedTag.firstChild.nodeValue, 3);
    if(this.selectedTag == null) return false;
    var retVals = { uri : this.selectedTag.getAttribute("uri"), name: sidebar.selectedTag.firstChild.nodeValue, newName: null};
    openDialog("chrome://lasuli/content/topicDialog.xul", "dlg-topic", "modal", retVals);
    if(retVals.newName != null){
      sidebar.selectedTag.firstChild.nodeValue = retVals.newName;
    }
  },
  doContextMenuOpenTopicInPorphyry: function(){
    debug("[lasuliSidebar.js::doContextMenuOpenTopicInPorphyry] selectedTag:" + sidebar.selectedTag.getAttribute("uri"), 3);
    if(this.selectedTag == null) return false;
      window.open(PORPHYRY_PREFIX + this.selectedTag.getAttribute("uri"));
  },
  doContextMenuOpenPorphyry : function(){
  	var stringBundle = document.getElementById("sbLasuli");
    var viewpointList = document.getElementById("viewpointList");
    if(viewpointList.selectedItem == null){
      alert(stringBundle.getString("sidebar.error.vpisnull"));
      return false;
    }
    window.open(PORPHYRY_PREFIX + viewpointList.selectedItem.value);
  },

  doContextMenuOpenViewpoint : function(){
  	var stringBundle = document.getElementById("sbLasuli");
    var viewpointList = document.getElementById("viewpointList");
    if(viewpointList.selectedItem == null){
    	alert(stringBundle.getString("sidebar.info.selectavp"));
      return false;
    }
    sidebar.doOpenViewpointTabPanel(viewpointList.selectedItem.label, viewpointList.selectedItem.value);
  },

  doChangeTab : function(){
    var tabsParent = document.getElementById("LaSuli_Sidebar_Tab");
    var viewpointUri = this.getSelectedPanelViewpointUri();
    debug("[sidebar::doChangeTab] viewpointUri:" + viewpointUri, 3);
    if(viewpointUri == null)
      tabsParent.setAttribute("disableclose", true);
    else
      tabsParent.setAttribute("disableclose", false);
  },

  doOpenViewpointTabPanel : function(name, href){
    var tabPanelsParent = document.getElementById("LaSuli_Sidebar_TabPanel");
    var tabsParent = document.getElementById("LaSuli_Sidebar_Tab");
    var tabPanels = document.getElementsByTagName("tabpanel");
    for (var i = 0; i < tabPanels.length; i++) {
      var uriOfTab = tabPanels[i].getAttribute("href");
      if(uriOfTab == href){
        debug("[lasuliSidebar.js::openViewpointTabPanel] tabPanel already opened!" ,2 );
        return;
      }
    }

    debug("[lasuliSidebar.js::openViewpointTabPanel] tabPanelsParent id:" + tabPanelsParent.getAttribute("id") ,2 );
    var tab = document.createElement('tab');
    var label = document.createElement('label');
    //var toolbarbutton = document.createElement('toolbarbutton');
    tab.setAttribute('href', href);
    tab.setAttribute('linkedpanel', 'tabpanel_' + MD5(href));
    //toolbarbutton.setAttribute('href', href);
    //toolbarbutton.addEventListener('click', sidebar.doCloseViewpointTabPanel,false);

    label.setAttribute('value', name);
    tab.appendChild(label);

    tabsParent.appendChild(tab);
//    tabsParent.appendChild(toolbarbutton);

    var tabPanel = document.createElement('tabpanel');
    tabPanel.setAttribute('href', href);
    tabPanel.setAttribute('id', 'tabpanel_' + MD5(href));
    tabPanelsParent.appendChild(tabPanel);

    var vboxContainer = document.createElement('vbox');
    vboxContainer.setAttribute('flex', '1');
    tabPanel.appendChild(vboxContainer);

    var vbox = document.createElement('vbox');
    vbox.setAttribute('href', href);
    vbox.setAttribute('id', 'tagcloud_' + MD5(href));
    //vbox.setAttribute('flex', '1');
    vbox.setAttribute('style', 'overflow: none');
    vboxContainer.appendChild(vbox);

    /*var splitter = document.createElement('splitter');
    splitter.setAttribute('collapse', 'after');
    splitter.setAttribute('resizebefore', 'closest');
    splitter.setAttribute('resizeafter', 'closest');
    vboxContainer.appendChild(splitter);

    var grippy = document.createElement('grippy');
    splitter.appendChild(grippy);*/

    vbox = document.createElement('vbox');
    vbox.setAttribute('href', href);
    vbox.setAttribute('id', 'fragment_' + MD5(href));
    vbox.setAttribute('flex', '1');
    vbox.setAttribute('style', 'overflow: auto');
    vboxContainer.appendChild(vbox);

    /*var label = document.createElement('label');
    label.setAttribute('value', href);
    tabPanel.appendChild(label);*/
    this.showFragmentsInViewpoints();
    showTagCloud(href);
  },

  doCloseViewpointTabPanel : function(){
    var uri = this.getSelectedPanelViewpointUri();
    if(uri == null)
    	return;

    var tabPanelsParent = document.getElementById("LaSuli_Sidebar_TabPanel");
    var tabsParent = document.getElementById("LaSuli_Sidebar_Tab");

    debug("[lasuliSidebar.js::doCloseViewpointTabPanel] remove tab panel:" + uri, 4);
    // remove tab panel
    var items = tabPanelsParent.getElementsByTagName('tabpanel');
    for (var i = 0; i < items.length; i++)
      if(items[i].hasAttribute("href") && items[i].getAttribute("href") == uri){
        if(tabPanelsParent.selectedPanel == items[i]){
          tabsParent.selectedIndex = 0;
        }
        tabPanelsParent.removeChild(items[i]);
      }

    // remove tabs and toolbarbutton
    var items = tabsParent.getElementsByTagName('tab');
    for (var i = 0; i < items.length; i++)
      if(items[i].hasAttribute("href") && items[i].getAttribute("href") == uri){
        tabsParent.removeChild(items[i]);
      }
   /* var items = tabsParent.getElementsByTagName('toolbarbutton');
    for (var i = 0; i < items.length; i++)
      if(items[i].hasAttribute("href") && items[i].getAttribute("href") == uri){
        tabsParent.removeChild(items[i]);
      }
*/
  },

  doScroll2Fragment: function(evt) {
  	var elementId = evt.target.getAttribute("fragment");
		var doc = content.document;
		var el = doc.getElementById(elementId);
		var valueT = 0, valueL = 0;
		do {
				valueT += el.offsetTop  || 0;
				valueL += el.offsetLeft || 0;
				el = el.offsetParent;
		} while (el);
		content.scrollTo(valueL, valueT);
  },

  doUpdateFragment: function(evt) {
    var startPos = evt.target.getAttribute("startPos");
    var endPos = evt.target.getAttribute("endPos");
    var colorIndex = evt.target.getAttribute("colorIndex");
    var originalColorIndex = evt.target.getAttribute("originalColorIndex");
    try{
      startPos = parseInt(startPos);
      endPos = parseInt(endPos);
      colorIndex = parseInt(colorIndex);
      originalColorIndex = parseInt(originalColorIndex);
    }catch(ex){return false;}

    var fragment = {};
    fragment.startPos = startPos;
    fragment.endPos = endPos;
    fragment.colorIndex = originalColorIndex;
    var viewpointUri = sidebar.getSelectedPanelViewpointUri();
    proxy.updateFragment(fragment, colorIndex, viewpointUri);
    sidebar.showFragments();
    highlighter.doFormatHtml();
    sidebar.showFragmentsInViewpoints();
    var viewpointUri = sidebar.getSelectedPanelViewpointUri();
    if(viewpointUri != null)
			  showTagCloud(viewpointUri);
  },

  doDeleteFragment: function(evt) {
    var startPos = evt.target.getAttribute("startPos");
    var endPos = evt.target.getAttribute("endPos");
    try{
      startPos = parseInt(startPos);
      endPos = parseInt(endPos);
    }catch(ex){return false;}

    var fragment = {};
    fragment.startPos = startPos;
    fragment.endPos = endPos;
    proxy.removeFragment(fragment);
    sidebar.showFragments();
    highlighter.doFormatHtml();
    sidebar.showFragmentsInViewpoints();
    var viewpointUri = sidebar.getSelectedPanelViewpointUri();
    if(viewpointUri != null)
			  showTagCloud(viewpointUri);
  },

  showEntityList : function(){
    if(htData.porps == null)
			return;

		var stringBundle = document.getElementById("sbLasuli");
    var puEntityList = document.getElementById('puEntityList');
    var captionEntity = document.getElementById('captionEntity');
    while (puEntityList.hasChildNodes()) puEntityList.removeChild(puEntityList.firstChild);

    captionEntity.label = stringBundle.getString("sidebar.info.noentity");

    for (var i = 0; i < htData.porps.length; i++)
    {
      var entity = htData.porps[i];
      if (entity.href != "") {
        var eName = entity.name;
        if(eName == "") eName = stringBundle.getString("sidebar.info.entitynoname");
        var menu = document.createElement('menuitem');
        menu.setAttribute('label', eName);
        menu.setAttribute('type', "radio");
        menu.setAttribute('href', entity.href);
        debug("[lasuliSidebar.js::showEntityList] entity.href:" + entity.href , 3);
        puEntityList.appendChild(menu);
        menu.addEventListener("click", this.doEntityChange, false);
        if(i == 0){
          captionEntity.label = eName;
          menu.setAttribute('checked', true);
          this.showPorps(entity.href);
        }
      }
    }
    if(htData.porps.length == 0)
      this.showPorps();
  },

  showFragments: function(){

    var fragmentContainer = document.getElementById("fragmentContainter");
		this.clearFragmentLabel(fragmentContainer);
		if(htData.fragments == null)
			return;

		for(i = 0; i < htData.fragments.length; i++){
			var f = htData.fragments[i];
			this.addFragmentLabel(fragmentContainer, f);
		}
	},

  showPorps : function(href){
    this.removeAttributes();
    this.removeResources();
    this.removeViewpoints();
    this.showViewpoints(href);
    if(href == null) return false;
    for(var i = 0; i < htData.porps.length; i++)
      if(htData.porps[i].href == href){
        for(var j=0; j < htData.porps[i].resources.length; j++)
            this.addResource(htData.porps[i].resources[j].name, htData.porps[i].resources[j].href);
        for(var j=0; j < htData.porps[i].attributes.length; j++)
            this.addAttribute(htData.porps[i].attributes[j].name, htData.porps[i].attributes[j].value);
        break;
      }
  },

  showFragmentsInViewpoints: function(){
    var panels = document.getElementsByTagName('tabpanel');
    for(var i = 0;i < panels.length; i++){
      var panel = panels[i];
      if(panel.hasAttribute("href")){
        var viewpointHref = panel.getAttribute("href");
        debug("[lasuliSidebar.js::showFragmentsInViewpoints] panel:" + viewpointHref,3);
        var fragmentContainer = null;
        try{
          fragmentContainer = document.getElementById('fragment_' + MD5(viewpointHref));
        }catch(ex) { break; }
        this.clearFragmentLabel(fragmentContainer);

        debug("[lasuliSidebar.js::showFragmentsInViewpoints] fragment numbers:" + htData.fragments.length,3);
        for(m = 0; m < htData.fragments.length; m++){
    			var f = htData.fragments[m];
    			if(f.viewpoints == null) continue;
    			for(var j=0; j < f.viewpoints.length; j++){
    			  debug("[lasuliSidebar.js::showFragmentsInViewpoints] viewpoint uri:" + f.viewpoints[j],3);
    			  if(f.viewpoints[j] == viewpointHref)
    			    this.addFragmentLabel(fragmentContainer, f);
    			}
    		}
      }
    }
  },

  showViewpoints : function(href){
    var filter = document.getElementById("cbViewpointFilter");
    this.removeViewpoints();

    if(filter.hasAttribute("checked")){
      if(href == null) return false;
      //debug("[lasuliSidebar.js::showViewpoints] filter.checked: " + filter.checked, 4);
      for(var i = 0; i < htData.porps.length; i++)
        if(htData.porps[i].href == href){
          for(var j=0; j < htData.porps[i].viewpoints.length; j++)
            this.addViewpoint(htData.porps[i].viewpoints[j].name, htData.porps[i].viewpoints[j].href);
          break;
        }
    }
    else
      for(var i = 0; i < htData.viewpoints.length; i++){
        //debug("[lasuliSidebar.js::showViewpoints] htData.viewpoints[i].name: " + htData.viewpoints[i].name, 4);
        this.addViewpoint(htData.viewpoints[i].name, htData.viewpoints[i].href);
      }
  },

  getPopupSource:function(){
    var node = document.popupNode;
    if(node.hasAttribute("uri")){
      debug("[lasuliSidebar.js::getPopupSource] popup source:" + node.getAttribute("uri"), 3);
      /*this.selectedTag = {};
      this.selectedTag.href = node.getAttribute("uri");
      this.selectedTag.name = node.firstChild.nodeValue;*/
      this.selectedTag = node;
      return;
    }
    this.selectedTag = null;
  },

  getSelectedPanelViewpointUri: function(){
    var tabPanelsParent = document.getElementById("LaSuli_Sidebar_TabPanel");
    var viewpointUri = null;
    if(tabPanelsParent.selectedIndex > 1 && tabPanelsParent.selectedPanel.hasAttribute("href"))
    {
        viewpointUri = tabPanelsParent.selectedPanel.getAttribute("href");
    }
    return viewpointUri;
  },

  addAttribute : function(attrName, attrValue){
    var attributeChilds = document.getElementById('attributeChilds');
    var item = document.createElement('treeitem');
    var row = document.createElement('treerow');
    var c1 = document.createElement('treecell');
    var c2 = document.createElement('treecell');
    c1.setAttribute('label', attrName);
    c2.setAttribute('label', attrValue);
    row.appendChild(c1);
    row.appendChild(c2);
    item.appendChild(row);
    attributeChilds.appendChild(item);
  },

  removeAttributes : function(){
    var attributeChilds = document.getElementById('attributeChilds');
    while (attributeChilds.hasChildNodes()) attributeChilds.removeChild(attributeChilds.firstChild);
  },

  addResource : function(resName, resHref){
    var resourceList = document.getElementById('resourceList');
    var item = document.createElement('listitem');
    item.setAttribute('label', resName);
    item.setAttribute('value', resHref);
    resourceList.appendChild(item);
  },

  removeResources : function(){
    var resourceList = document.getElementById('resourceList');
    while (resourceList.hasChildNodes()) resourceList.removeChild(resourceList.firstChild);
  },

  addViewpoint : function(vpName, vpHref){
    var viewpointList = document.getElementById('viewpointList');
    var items = viewpointList.getElementsByTagName('listitem');
    for(var i=0; i < items.length; i++){
      var item = items[i];
      var vpUrl = item.getAttribute("value");
      if(vpUrl.length > 0 && vpUrl == vpHref)
        return;
    }
    var item = document.createElement('listitem');
    item.setAttribute('label', vpName);
    item.setAttribute('value', vpHref);
    viewpointList.appendChild(item);
  },

  removeViewpoints : function(){
    var viewpointList = document.getElementById('viewpointList');
    while (viewpointList.hasChildNodes()) viewpointList.removeChild(viewpointList.firstChild);
  },

  addFragmentLabel: function(fragmentContainer, fragment){
		var el = this.creatFragmentLabel(fragment);
		fragmentContainer.appendChild(el);
	},

  creatFragmentLabel: function(fragment){
  	var stringBundle = document.getElementById("sbLasuli");
    debug("[lasuliSidebar.js::creatFragmentLabel] fragment:" + dump(fragment), 3);
    var groupElement = document.createElement('groupbox');
		var labelElement = document.createElement('label');

    var popupElements = document.getElementsByTagName('popup');
    var popupExist = false;
    for(var i = 0;i < popupElements.length; i++)
      if(popupElements[i].hasAttribute("id") && popupElements[i].getAttribute("id") == ("popup_" + fragment.startPos + "_" + fragment.endPos))
      {
        popupExist = true;
        break;
      }
    if(!popupExist){
  		// Create popup menu
  		var popupsetElement = document.createElement('popupset');
  		var popupElement = document.createElement('popup');
  		var menuitemElement = document.createElement('menuitem');
  		popupElement.setAttribute("id", "popup_" + fragment.startPos + "_" + fragment.endPos);
  		popupsetElement.appendChild(popupElement);

  		menuitemElement.setAttribute("label",stringBundle.getString("sidebar.info.scroll"));
  		menuitemElement.setAttribute("fragment", "ht_fragment_" + fragment.startPos + "_" + fragment.endPos);
  		menuitemElement.addEventListener("click", sidebar.doScroll2Fragment, false);
  		popupElement.appendChild(menuitemElement);
  		popupElement.appendChild(document.createElement('menuseparator'));

      for(var i=0; i  <	COLORS.length; i++){
        menuitemElement = document.createElement('menuitem');
        menuitemElement.setAttribute("label",stringBundle.getString("sidebar.info.setcolor") + (i+1));
        menuitemElement.setAttribute("startPos",fragment.startPos);
    		menuitemElement.setAttribute("endPos",fragment.endPos);
    		menuitemElement.setAttribute("originalColorIndex",fragment.colorIndex);
    		menuitemElement.setAttribute("colorIndex",i);
    		menuitemElement.setAttribute("style", "-moz-appearance: none !important; background-color:" + COLORS[i] + " !important;");
    		menuitemElement.addEventListener("click", sidebar.doUpdateFragment, false);
    		popupElement.appendChild(menuitemElement);
      }

  		popupElement.appendChild(document.createElement('menuseparator'));
  		menuitemElement = document.createElement('menuitem');
  		menuitemElement.setAttribute("label",stringBundle.getString("sidebar.info.deletefragment"));
  		menuitemElement.setAttribute("startPos",fragment.startPos);
  		menuitemElement.setAttribute("endPos",fragment.endPos);
  		menuitemElement.addEventListener("click", sidebar.doDeleteFragment, false);
  		popupElement.appendChild(menuitemElement);
  		groupElement.appendChild(popupsetElement);
    }

		//var labelElement = document.createElementNS("http://www.w3.org/1999/xhtml","html:div");
		labelElement.appendChild(document.createTextNode(fragment.content));
		//labelElement.setAttribute("id", fragment.startPos + "+" + fragment.endPos);
		groupElement.setAttribute("context", "popup_" + fragment.startPos + "_" + fragment.endPos);
		groupElement.setAttribute("style", "background-color:" + COLORS[fragment.colorIndex] + ";");
		groupElement.setAttribute("id", "group_" + fragment.startPos + "_" + fragment.endPos);
		groupElement.appendChild(labelElement);
		return groupElement;
  },

	clearFragmentLabel: function(fragmentContainer){
		while (fragmentContainer.firstChild) {
  		fragmentContainer.removeChild(fragmentContainer.firstChild);
		}
	}
}

function openUrl(resourceUrl){
  if((typeof resourceUrl)!= "string" || !resourceUrl.isURL())
    return;

  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].
      getService(Components.interfaces.nsIWindowMediator);
  var browserEnumerator = wm.getEnumerator("navigator:browser");
  var browserInstance = browserEnumerator.getNext().getBrowser();

  // Create tab
  var newTab = browserInstance.addTab(resourceUrl);

  // Focus tab
  browserInstance.selectedTab = newTab;
  browserInstance.focus();
}

function openViewpointDialog(){
  var retVals = { name : null, uri:null};
  openDialog("chrome://lasuli/content/viewpointDialog.xul", "dlg-viewpoint", "modal", retVals);
  if(retVals.uri != null){
    proxy.getViewpoints();
    sidebar.doFilterViewpoints();
  }
}

var urlBarListener = {
  QueryInterface: function(aIID)
  {
   if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
       aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
       aIID.equals(Components.interfaces.nsISupports))
     return this;
   throw Components.results.NS_NOINTERFACE;
  },

  onLocationChange: function(aProgress, aRequest, aURI)
  {
    sidebar.doUriChange(aURI.spec);
  },

  onStateChange: function(aWebProgress, aRequest, aFlag, aStatus)
  {
   var STATE_START = Components.interfaces.nsIWebProgressListener.STATE_START;
   var STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;
   // If you use myListener for more than one tab/window, use
   // aWebProgress.DOMWindow to obtain the tab/window which triggers the state change
   if(aFlag & STATE_START)
   {
     // This fires when the load event is initiated
     // TODO disable highlight menu
   }
   if(aFlag & STATE_STOP)
   {
     // This fires when the load finishes
     sidebar.doDocumentLoaded();
   }
   return 0;
  },

  onProgressChange: function() {},
  onStatusChange: function() {},
  onSecurityChange: function() {},
  onLinkIconAvailable: function() {}
};

var highlighter = {
  doFormatHtml: function(docHtml){
		var posX = 0;
		var posY = 0;
		var html = "";
		if(htData.fragments == null){
			debug("[lasuliSidebar.js::doFormatHtml]************************** highLightHtml **************************",1);
			debug("[lasuliSidebar.js::doFormatHtml] this._fragments is null!",1);
			debug("[lasuliSidebar.js::doFormatHtml]************************** highLightHtml **************************",1);
			return false;
		}
		if(docHtml == null)
		  docHtml = htData.docHtml;
		debug("[lasuliSidebar.js::doFormatHtml] ========================html source to highlight ==================",5);
		debug(docHtml,5);
		debug("[lasuliSidebar.js::doFormatHtml] ========================html source to highlight ==================",5);
		var offsetLength = 0;
		debug("[lasuliSidebar.js::doFormatHtml] highLightHtml: fragment.size()=" + htData.fragments.length,2);
		debug("[lasuliSidebar.js::doFormatHtml] highLightHtml:  doucment source length=" + docHtml.length,2);
		//if(htData.getSize() > 0) this._fragments.sort();
		for(var i=0; i < htData.fragments.length; i++){
			var highlight = {};
			var frag = htData.fragments[i];
			highlight.startPos = frag.startPos;
			highlight.endPos = frag.endPos;
			highlight.colorIndex = frag.colorIndex;
			highlight.content = frag.content;

			highlight.originalLength = frag.endPos-frag.startPos;
			debug("[lasuliSidebar.js::doFormatHtml] startPos:" + highlight.startPos + " Length:" + highlight.originalLength,4);
			highlight.originalHtml = docHtml.substr(highlight.startPos, highlight.originalLength);
			debug("[lasuliSidebar.js::doFormatHtml] originalHtml:" + highlight.originalHtml,4);
			highlight.highLightedHtml = HT_Selection.highLightByIndexOf(highlight.originalHtml, highlight.colorIndex);
			highlight.highLightedHtml = "<hypertopic type=\"start\" id=\"ht_fragment_" + highlight.startPos + "_" + highlight.endPos + "\"></hypertopic>" + highlight.highLightedHtml
															  + "<hypertopic type=\"end\" id=\"ht_fragment_end_" + highlight.startPos + "_" + highlight.endPos + "\"></hypertopic>";
			debug("[lasuliSidebar.js::doFormatHtml] highLightedHtml:" + highlight.highLightedHtml,4);
			/*highlight.highLightedLength = highlight.highLightedHtml.length;
			debug("[hypertopic.js] highLightedLength:" + highlight.highLightedLength,4);

			highlight.offsetPosX = highlight.startPos + offsetLength;
			offsetLength += highlight.highLightedLength - highlight.originalLength;
			highlight.offsetPosY = highlight.endPos + offsetLength;
			debug("[hypertopic.js] offsetPosX:" + highlight.offsetPosX,4);
			debug("[hypertopic.js] offsetPosY:" + highlight.offsetPosY,4);*/

			//this._fragments.fragments[i] = highlight;
			posY = highlight.startPos;
			html += docHtml.substring(posX,posY) + highlight.highLightedHtml;
			posX = highlight.endPos;
		}
		html += docHtml.substring(posX);
		html = html + HIGHLIGHT_TAG;
		debug("[lasuliSidebar.js::doFormatHtml] ======================== highlighted html source ==================",5);
		debug(html,5);
		debug("[lasuliSidebar.js::doFormatHtml] ======================== highlighted html source ==================",5);
		if(htData.fragments.length > 0)
		  mainWindow.getBrowser().contentDocument.documentElement.innerHTML = html;
		//debug("[hypertopic.js] html:" + html,5);
		//var sidebarWindow = document.getElementById("sidebar").contentWindow;
		//sidebarWindow.domLoader.doHighlight(html);
  }
};
window.addEventListener("load", function(){sidebar.init(); }, true);